package logic

import (
	"community/models/mysqlinit"
	"context"
	"fmt"

	"community/communityrpc/communityrpc"
	"community/communityrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListCommentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListCommentLogic {
	return &ListCommentLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListCommentLogic) ListComment(in *communityrpc.ListCommentRequest) (*communityrpc.ListCommentResponse, error) {
	// todo: add your logic here and delete this line
	var post mysqlinit.Post

	mysqlinit.DB.Debug().Where("id = ?", in.PostId).Find(&post)

	if post.ID == 0 {
		return nil, fmt.Errorf("没有此帖子，请重新输入")
	}
	var list []mysqlinit.CommentName
	mysqlinit.DB.Table("comments").Select("users.name, comments.comm_text").Joins("left join users on comments.user_id = users.id").Where("post_id =?", in.PostId).Scan(&list)
	var comm []*communityrpc.CommtList
	for _, i := range list {
		commtList := communityrpc.CommtList{
			Name:     i.Name,
			CommText: i.CommText,
		}
		comm = append(comm, &commtList)
	}

	return &communityrpc.ListCommentResponse{
		Lists:   comm,
		UserId:  post.UserId,
		Image:   post.Image,
		Content: post.Content,
	}, nil
}
